package org.jsola.hr.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.sm4.SM4Utils;
import org.jsola.hr.dto.syncSocDTO.*;
import org.jsola.hr.entity.EmpInfoDO;
import org.jsola.hr.entity.ZtcConfigDO;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author lyh
 */
@Slf4j
public class QdSocWebSite {

    /**
     * 青岛社保查询数据接口
     */
    public static String getPayDetailInfo(String startDate, String endDate, String cookie, int pageNo) {
        HttpResponse<String> response = Unirest.post("http://12333.qingdao.gov.cn/wssb2/work/f71010308/getOrgnPayDetlInfo.action")
                .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .header("Accept", "text/plain, */*; q=0.01")
                .header("Cookie", cookie)
                .queryString("qsny", startDate)
                .queryString("zzny", endDate)
                .queryString("jfbz", "1")
                .queryString("pageIndex", pageNo)
                .queryString("pageSize", "100")
                .asString();
        if (response.isSuccess()) {
            return response.getBody();
        } else {
            throw new ParamException("请重新登录社保网站");
        }
    }

    /**
     * 青岛公积金获取token接口
     */
    public static String getQDGJJIndexToken(String cookie) {
        Document document = null;
        try {
            document = Jsoup.connect("http://wt.qdgjj.com:1080/Index.aspx?dt=781")
                    .header("Content-Type", "text/html; charset=utf-8")
                    .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
                    .header("Cookie", cookie)
                    .get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return document.getElementById("token").attr("value");
    }

    /**
     * 青岛公积金获取数据接口
     */
    public static String getPayDetailInfoPf(String cookie, int pageNo, String dt) {
        String token = getQDGJJIndexToken(cookie);
        HttpResponse<String> response = Unirest.post("http://wt.qdgjj.com:1080/gateway.ashx?dt=" + dt)
                .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .header("Accept", "application/json, text/javascript, */*; q=0.01")
                .header("Cookie", cookie)
                .queryString("SVRNAME", "FusrQuyPerInfoAcctLis")
                .queryString("page", pageNo)
                .queryString("PA_STAT", "01")
                .queryString("rows", "30")
                .queryString("TOKEN", token)
                .asString();
        if (response.isSuccess()) {
            return response.getBody();
        } else {
            throw new ParamException("请重新登录公积金网站");
        }
    }

    /**
     * 获取青岛社保缴费比例
     */
    public static String getCardinalityDefault(String cookie) {
        HttpResponse<String> response = Unirest.post("http://12333.qingdao.gov.cn/wssb2/work/f71010314/getJffl.action")
                .header("Accept", "text/plain, */*; q=0.01")
                .header("Cookie", cookie)
                .asString();
        return response.getBody();
    }

    /**
     * 获取青岛社保编号
     */
    public static String getUserInfo(String cookie) {
        HttpResponse<String> response = Unirest.get("http://hrsswb.qingdao.gov.cn:81/cas-server/system/userInfo")
                .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
                .header("Cookie", cookie)
                .asString();
        String body = response.getBody();
        int companyNumIndex = body.lastIndexOf("单位编号：");
        return body.substring(companyNumIndex + 5, companyNumIndex + 15);
    }

    /**
     * 获取AccessToken
     */
    public static String getAccessToken(ZtcConfigDO ztcConfigDO, String loginName, String password) {
        JSONObject bodyJson = new JSONObject();
        // 入参
        bodyJson.put("busiid", "ZQ3101");
        bodyJson.put("appid", ztcConfigDO.getAppId());
        bodyJson.put("loginname", loginName);
        bodyJson.put("password", password);
        HttpResponse<String> response;
        try {
            // 获取AccessToken
            response = Unirest.post("http://221.215.38.123:7001/qdaio-gett/case/saveApply")
                    .header("Content-type", "application/json")
                    .body(bodyJson.toJSONString())
                    .asString();
        } catch (Exception e) {
            throw new ParamException("未配置白名单");
        }
        String body = response.getBody();
        String decrypt = SM4Utils.getDecStr(body, ztcConfigDO.getOfficialKey());
        JSONObject accessTokenJson = JSONObject.parseObject(decrypt);
        String respCode = (String) accessTokenJson.get("respCode");
        if ("0".equals(respCode)) {
            throw new ParamException((String) accessTokenJson.get("respMsg"));
        } else {
            return (String) accessTokenJson.get("access_token");
        }
    }

    /**
     * 校验青岛社保增員人员是否正确
     */
    public static QdIncrementCheckDTO checkIncrementEmp(String idCard, String cookie) {
        QdIncrementCheckDTO result = new QdIncrementCheckDTO();
        HttpResponse<String> response = Unirest
                .post("http://12333.qingdao.gov.cn/wssb2/work/f71010101/query.action?sfzhm=" + idCard)
                .header("Content-Type", "text/html;charset=UTF-8")
                .header("Accept", "application/json, text/javascript, */*; q=0.01")
                .header("Cookie", cookie)
                .asString();
        String body = response.getBody();
        if (body.startsWith("{") && body.endsWith("}")) {
            JSONObject checkResult = JSON.parseObject(body);
            result = JSON.toJavaObject(checkResult, QdIncrementCheckDTO.class);
        } else {
            result.setErrorInfo(response.getBody());
        }
        return result;
    }

    /**
     * 校验青岛社保减员人员是否正确
     */
    public static QdAttritionCheckDTO checkAttritionEmp(String idCard, String cookie) {
        QdAttritionCheckDTO result = new QdAttritionCheckDTO();
        HttpResponse<String> response = Unirest
                .post("http://12333.qingdao.gov.cn/wssb2/work/f71010102/query.action?yxzjhm=" + idCard)
                .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .header("Accept", "application/json, text/javascript, */*; q=0.01")
                .header("Cookie", cookie)
                .asString();
        String body = response.getBody();
        if (body.startsWith("{") && body.endsWith("}")) {
            JSONObject checkResult = JSON.parseObject(body);
            result = JSON.toJavaObject(checkResult, QdAttritionCheckDTO.class);
        } else {
            result.setErrorInfo(response.getBody());
        }
        return result;
    }

    /**
     * 获取就业登记单位
     */
    public static List<QdEmploymentRegistrationUnit> getEmploymentRegistrationUnit(String cookie) {
        HttpResponse<String> response;
        try {
            response = Unirest
                    .get("http://12333.qingdao.gov.cn/wssb2/work/f70010101/getJydjdw.action?_=" + System.currentTimeMillis())
                    .header("Accept", "text/plain, */*; q=0.01")
                    .header("Cookie", cookie)
                    .header("Host", "12333.qingdao.gov.cn")
                    .asString();
        } catch (Exception e) {
            throw new ParamException("获取就业登记单位失败,请稍后再尝试进行增员同步");
        }
        String employmentRegistrationUnit = response.getBody();
        return JSONObject.parseArray(employmentRegistrationUnit, QdEmploymentRegistrationUnit.class);
    }

    /**
     * 增员
     */

    public static String increment(EmpInfoDO empInfoDO, String appId, QdIncrementCheckDTO qdIncrementCheckDTO,
                                   String accessToken, String cookie) {
        QdWebSiteIncrementExtraInfo extraInfo = qdIncrementCheckDTO.getExtraInfo();
        // 流水号
        String serialNumber = DateUtils.getDateStr(new Date(), "yyyyMMddHHmmss") +
                RandomStringUtils.random(6, false, true);
        JSONObject bodyJson = new JSONObject();
        // 入参
        bodyJson.put("appid", appId);
        bodyJson.put("access_token", accessToken);

        JSONObject bodyParams = new JSONObject();
        // 接口ID  写死 ZQ3102
        bodyParams.put("busiid", "ZQ3102");
        // 流水号
        bodyParams.put("lshid", serialNumber);
        // 单位的社保编号  10000002698131
        bodyParams.put("data01", extraInfo.getCompanyNum());
        //bodyParams.put("data01", "3703732699");
        // 国别
        bodyParams.put("data02", "CHN");
        // 证件类型
        bodyParams.put("data03", qdIncrementCheckDTO.getYxzjlx());
        // 证件号码
        bodyParams.put("data04", empInfoDO.getIdCard());
        // 姓名
        bodyParams.put("data05", empInfoDO.getName());
        // 性别
        bodyParams.put("data06", empInfoDO.getGender());
        // 出生日期
        ParamException.notNull(empInfoDO.getBirthday(), "员工出生日期未填写,不可进行增员操作");
        bodyParams.put("data07", empInfoDO.getBirthday().substring(0, 10).replace("-", ""));
        // 民族
        bodyParams.put("data08", qdIncrementCheckDTO.getMz());
        // 移动电话号码
        bodyParams.put("data17", empInfoDO.getPhone());
        // 户籍所在地的省份代码
        bodyParams.put("data18", qdIncrementCheckDTO.getProvince());
        // 户籍所在地的市级代码
        bodyParams.put("data19", qdIncrementCheckDTO.getCity());
        // 户籍所在地的区代码
        bodyParams.put("data20", qdIncrementCheckDTO.getHkszdxzqh());
        // 户籍地地址
        bodyParams.put("data22", qdIncrementCheckDTO.getAddressHousehold());
        // 联系地址
        bodyParams.put("data23", qdIncrementCheckDTO.getTxdz());
        // 户口性质
        bodyParams.put("data24", qdIncrementCheckDTO.getHkxz());
        // 本次参保开始年月
        bodyParams.put("data25", extraInfo.getCurrentInsuredStartDate());
        // 工资
        bodyParams.put("data26", extraInfo.getWages());
        // 灵活性就业人员是否参加医疗保险
        bodyParams.put("data30", extraInfo.getWhetherMe());
        // 是否参加就业登记
        bodyParams.put("data31", extraInfo.getEmploymentPermit());
        // 工种代码
        bodyParams.put("data32", extraInfo.getJobs());
        // 劳动合同类型
        bodyParams.put("data33", extraInfo.getLaborContractsType());
        // 合同签订日期
        bodyParams.put("data34", extraInfo.getContractsSignedDate());
        // 合同签订日期
        bodyParams.put("data35", extraInfo.getEmploymentType());
        // 合同开始日期
        bodyParams.put("data36", extraInfo.getContractsStartDate());
        // 合同终止日期
        bodyParams.put("data37", extraInfo.getContractsEndDate());
        // 就业单位编号
        bodyParams.put("data38", extraInfo.getEmploymentCompanyNum());
        bodyJson.put("params", SM4Utils.getEncStr(bodyParams.toString(), "6r92SARVzc2Lg3u0"));
        // 调增员接口
        HttpResponse<String> response = Unirest.post("http://221.215.38.123:7001/qdaio-gett/case/saveApply")
                .header("Content-type", "application/json")
                .body(bodyJson.toJSONString())
                .asString();
        return response.getBody();
    }

    /**
     * 减员
     */
    public static String attrition(String accessToken, String appId, EmpInfoDO empInfoDO,
                                   QdWebSiteAttritionExtraInfo extraInfo) {
        // 流水号
        String serialNumber = DateUtils.getDateStr(new Date(), "yyyyMMddHHmmss") +
                RandomStringUtils.random(6, false, true);
        JSONObject bodyJson = new JSONObject();
        // 入参
        bodyJson.put("appid", appId);
        bodyJson.put("access_token", accessToken);
        JSONObject bodyParams = new JSONObject();
        // 接口ID  写死 ZQ3103
        bodyParams.put("busiid", "ZQ3103");
        // 流水号
        bodyParams.put("lshid", serialNumber);
        // 单位的社保编号
        //bodyParams.put("data01", getUserInfo(cookie));
        bodyParams.put("data01", extraInfo.getCompanyNum());
        // 证件类型
        bodyParams.put("data02", extraInfo.getCredentialsType());
        // 证件号码
        bodyParams.put("data03", empInfoDO.getIdCard());
        // 姓名
        bodyParams.put("data04", empInfoDO.getName());
        // 本次停保开始年月
        bodyParams.put("data05", extraInfo.getStopBeginDate());
        // 是否就业解聘
        bodyParams.put("data06", extraInfo.getEmploymentDismissal());
        // 解聘原因
        bodyParams.put("data07", extraInfo.getDismissalCause());
        // 解除合同时间
        bodyParams.put("data08", extraInfo.getRelieveContractTime());
        // 就业单位编号
        bodyParams.put("data09", extraInfo.getJobCompanyNum());
        bodyJson.put("params", SM4Utils.getEncStr(bodyParams.toString(), "6r92SARVzc2Lg3u0"));
        // 获取AccessToken
        HttpResponse<String> response = Unirest.post("http://221.215.38.123:7001/qdaio-gett/case/saveApply")
                .header("Content-type", "application/json")
                .body(bodyJson.toJSONString())
                .asString();
        return response.getBody();
    }

    public static void main(String[] args) {
        List<QdEmploymentRegistrationUnit> employmentRegistrationUnit = getEmploymentRegistrationUnit("WMONID=5tNvbhvjDOC; _trs_uv=km452f7t_4584_fc4u; JSESSIONID=p8whLQ2ZoZaOUa6i-ARM433r1tLrNdZAvnUZrSTMStgmFNRH6Pg3!-2102365355; cookie=36925438; _sid=22222fbb76c152a0de664f85f11f774703386811a63d03b22d47c243bbe0b4b5");
        System.out.println(employmentRegistrationUnit);
    }
}
